<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Query\CategoryQuery;
use App\Model\GoodsPrice;
use Illuminate\Http\Request;
use Cookie;
use Log;
use SplFileObject;

class GoodsPriceController extends Controller
{
    /**
     * 商品価格設定
     * 商品価格設定一覧
     */
    function queryGoodPrice(Request $request)
    {
        try{
            $goodsPrice = new GoodsPrice();
            $corp_id=Cookie::get('price_sel_corp_id');
            $priceData = $goodsPrice->getGoodsPriceByCorpId($corp_id);
            return view('admin.goods_pricelist', array(
                'priceData' => $priceData
            ));
        }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

    function getGoodsByCateId($cateId)
    {
       try{
            $goodsPrice = new GoodsPrice();
            $goodsCode = $goodsPrice->getGoodsCodeByCateId($cateId);
            return $goodsCode;
        }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

    /**
     * 商品価格設定
     * 商品価格設定一覧
     */
    function index(Request $request)
    {
       try{
            $priceId = $request->input('price_id');
            $goodsPrice = new GoodsPrice();
            $priceData = $goodsPrice->getGoodsPriceInfoByPriceId($priceId);

            $cateCode = $goodsPrice->getCateCode();
            $corpName = $goodsPrice->getCorpName();

            $goodsCode = [];

            $priceInfo = [
                $priceData,
                $cateCode,
                $goodsCode,
                $corpName
            ];
            if (!empty($priceData)) {
                $CateId = $priceData[0]->category_id;
                $goodsCode = $goodsPrice->getGoodsCodeByCateId($CateId);
                $priceInfo[2] = $goodsCode;
                $priceInfo[3] = $corpName;
                return view('admin.goods_price', array(
                    'price' => $priceInfo
                ));
            } else {
                $goodsCode = $goodsPrice->getGoodsCode();
                $priceInfo[2] = $goodsCode;
                $priceInfo[3] = $corpName;
                return view('admin.goods_price', array(
                    'price' => $priceInfo
                ));
            }
        }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

    /**
     * 商品価格設定
     * 商品価格設定情報を登録する
     */
    public function addGoodPrice(Request $request)
    {
       try{
            $goodsPrice = new GoodsPrice();
            $goodsPriceInfo = $request->input('PriceData');
            $price_id = $goodsPriceInfo['goods_price_id'];
            $corp_id=Cookie::get('price_sel_corp_id');
            $goodsPriceInfo["corp_id"]=$corp_id;

            if (empty($price_id)) {

                $flag = $goodsPrice->addGoodsPrice($goodsPriceInfo);

                if($flag){
                    return redirect('/admin/goods_pricelist')->with('success', '新規成功！');
                }
            } else {

                $goodsPriceInfo['updated_at'] = now();
                $flag = $goodsPrice->updGoodsPrice($goodsPriceInfo);
                if ($flag) {
                    return redirect('/admin/goods_pricelist')->with('success', '修正成功！');
                }
            }
        }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

    /**
     * 商品価格設定
     * 商品価格設定情報を削除する
     */
    public function delGoodPrice(Request $request)
    {
       try{
            $goods_price_id = $request->input('price_id');

            $goodsPrice = new GoodsPrice();
            $flag = $goodsPrice->delGoodsPrice($goods_price_id);

            if ($flag) {
                return redirect('/admin/goods_pricelist')->with('success', '削除成功！');
            }
        }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

    /**
     * 商品価格設定
     * 商品価格設定情報 CSV取り組み
     */
    public function inputCsv(Request $request)
    {
       try{
            setlocale(LC_ALL, 'ja_JP.UTF-8');

            // アップロードしたファイルを取得
            // 'csv_file' はCSVファイルインポート画面の inputタグのname属性
            $uploaded_file = $request->file('csv_file');
            $filecsv = $_FILES['csv_file'];
            // ファイル空の判断
            // ファイルフォーマットの判断
            $file_type = substr(strstr($filecsv['name'], '.'), 1);
            if ($file_type != 'csv') {
                echo "<script type=\"text/javascript\">alert(\"ファイルフォーマットのエラーです,もう一度アップロードしてください!\");window.history.go(-1);</script>";
                exit();
            }

            // アップロードしたファイルの絶対パスを取得
            $file_path = $request->file('csv_file')->path($uploaded_file);
            $file = new SplFileObject($file_path);
            $file->setFlags(SplFileObject::READ_CSV);

            $row_count = 1;
            $flag = false;
            // ここで値をデータベースに保存したりする
            $goodsPrice = new GoodsPrice();
            foreach ($file as $row) {

                if (isset($row[0]) && ! empty($row[0])) {
                    //var_dump($row);exit;
                    // 1行目のヘッダーは取り込まない
                    if ($row_count > 1) {

                        $corp_id = 1;
                        $goods_id = "";
                        $invoice_rate = 0;
                        $invoice_price = 0;
                        if (isset($row[0]) && ! empty($row[0])) {
                            $corp_id = $row[0];
                        }
                        if (isset($row[1]) && ! empty($row[1])) {
                            $goods_id = $row[1];
                        }
                        if (isset($row[2]) && ! empty($row[2])) {
                            $invoice_rate = $row[2];
                        }
                        if (isset($row[3]) && ! empty($row[3])) {
                            $invoice_price = $row[3];
                        }
                        if (isset($row[4]) && ! empty($row[4])) {
                            $invoice_rate = $row[4];
                        }
                        if(empty($goods_id)) {
                            continue;
                        }
                        $goodsPriceInfo = array();
                        $goodsPriceInfo['corp_id'] = $corp_id;
                        $goodsPriceInfo['goods_id'] = $goods_id;
                        $goodsPriceInfo['invoice_rate'] = $invoice_rate;
                        $goodsPriceInfo['invoice_price'] = $invoice_price;
                        $goodsPriceInfo['created_at'] = now();
                        $goodsPriceInfo['updated_at'] = now();
                        $goodsPriceInfo['delete_flg'] = 0;
                        $corp_id = cookie::get('corp_id');
                        $goodsPriceInfo['corp_id'] = $corp_id;
                        $goodsPriceInfo['goods_price_id'] = '';
                         $goodsPrice->addGoodsPrice($goodsPriceInfo);
                    }
                }

                $row_count ++;
            }
            if ($flag) {
                return redirect('/admin/goods_pricelist')->with('success', '取込成功！');
            }
       }catch (\Exception $e){
           \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
       }
    }
}
